package com.gepengjun.lims.controler;


import com.gepengjun.lims.entity.*;
import com.gepengjun.lims.service.PermissionService;
import com.gepengjun.lims.service.RefPermissionRoleService;
import com.gepengjun.lims.service.RefRoleUserService;
import com.gepengjun.lims.util.JsonResult.Result;
import com.gepengjun.lims.util.JsonResult.ResultUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jun
 * @since 2018-08-19
 */
@Controller
@RequestMapping("/lims/permission")
public class PermissionController {

    protected static final org.slf4j.Logger logger = LoggerFactory.getLogger(PermissionController.class);

    @Autowired
    private PermissionService permissionService;

    @RequestMapping(value = "/leftMenu",method = RequestMethod.GET)
    public String leftMenu(Permission permission,ModelMap map){

        List<Permission> permissionList = permissionService.findLeftMenus(permission.getPermissionId());
        map.addAttribute("permissionList",permissionList);
        return "permission/leftMenu";
    }

    @PostMapping("/roleAuthorize")
    @ResponseBody
    public Result roleAuthorize(HttpServletRequest request, Role role, String permissionIds){
        if (role != null && role.getRoleId() != null){
            if (permissionService.roleAuthorize(role.getRoleId(),permissionIds)){
                //授权成功之后,将session里的用户权限码  更新
                Session session = SecurityUtils.getSubject().getSession();
                User user = (User) session.getAttribute("user");
                List<Permission> permissionList = permissionService.findByUserId(user.getUserId());
                List<String> permissionStrList = new ArrayList<>();
                for (Permission permission:permissionList){
                    permissionStrList.add(permission.getPermissionStr());
                }
                request.getSession().setAttribute("permissionStrList",permissionStrList);

                return ResultUtil.success("授权成功");
            }
        }
        return ResultUtil.error(-2,"授权失败：角色为空");
    }

}

